//
//  ChooseCar.m
//  ChooseCar
//
//  Created by Xue Senhong on 15/5/19.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "ChooseCarController.h"


@interface ChooseCarController ()<UITableViewDataSource,UITableViewDelegate, UIScrollViewDelegate,UIGestureRecognizerDelegate, SecondCellDelegate,SerialSend>

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)NSMutableArray *secondCellHotMaster;

@property (nonatomic, retain)NSMutableArray *secondCellHotSerial;

@property (nonatomic, retain)NSMutableArray *brandArray;

@property (nonatomic, retain)NSMutableDictionary *brandDic;

@property (nonatomic, retain)UITableView *listTableView;

@property (nonatomic)BOOL didselect;

@property (nonatomic, retain)NSMutableArray *listArray;

@property (nonatomic, retain)UIImageView *listTableImage;

@property (nonatomic, retain)UIView *listView;

@property (nonatomic, retain) UIBarButtonItem *area;
@end

@implementation ChooseCarController
- (void)dealloc
{
    [_listView release];
    [_listTableImage release];
    [_listTableView release];
    [_brandDic release];
    [_brandArray release];
    [_secondCellHotMaster release];
    [_secondCellHotSerial release];
    [_tableView release];
    [_listArray release];
    [_area release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // SecondCell需要的两个数组
        self.secondCellHotMaster = [NSMutableArray array];
        self.secondCellHotSerial = [NSMutableArray array];
        
        // brand列表需要的数组和字典
        self.brandArray = [NSMutableArray array];
        self.brandDic = [NSMutableDictionary dictionary];
        
        NSMutableArray *bigArray = [NSMutableArray array];
        bigArray = [BrandDatabase selectAll];
        
        self.listArray = [NSMutableArray array];
        
        [self editiBrandArray:bigArray];
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    self.navigationItem.title = @"爱选车";
    self.navigationController.navigationBar.translucent = NO;
    
    [super viewDidLoad];
    [self startConnect];
}

#pragma headView
- (void)creatHeadView
{
    NSArray *arr = [NSArray arrayWithObjects:@"销量排行", @"上市新车", nil];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight * 120 / 667)];
    for (int i = 0; i < arr.count; i++) {
        UIButton *cellButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth * 144 / 375 * i + kScreenWidth * 50 / 375, 0, kScreenWidth * 94 / 375, kScreenHeight * 120 / 667)];
        UIImageView *cellImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth * 25 / 375, kScreenHeight * 30 / 667, kScreenWidth * 44 / 375, kScreenHeight * 44 / 667)];
        [cellImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png", i + 2]]];
        [cellButton addSubview:cellImage];
        UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth * 12 / 375, kScreenHeight * 84 / 667, kScreenWidth * 71 / 375, kScreenHeight * 17 / 667)];
        
        [cellButton addTarget:self action:@selector(headButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        cellLabel.text = [arr objectAtIndex:i];
        cellLabel.textAlignment = NSTextAlignmentCenter;
        cellLabel.font = [UIFont systemFontOfSize:14];
        [cellButton addSubview:cellLabel];
        [headView addSubview:cellButton];
        
        [cellButton release];
        [cellImage release];
        [cellLabel release];
    }
    self.tableView.tableHeaderView = headView;
    [headView release];
    
}

- (void)headButtonAction:(UIButton *)button
{
     if (button.frame.origin.x == kScreenWidth * 144 / 375 + kScreenWidth * 50 / 375){
        
        NewCarViewController *new = [[NewCarViewController alloc] init];
        new.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:new animated:YES];
        [new release];
     } else {
         SellSortViewController *sell = [[SellSortViewController alloc] init];
         
         sell.hidesBottomBarWhenPushed = YES;
         
         [self.navigationController pushViewController:sell animated:YES];
         
         [sell release];
     }
}

#pragma 热门推荐数据的网络请求
- (void)startConnect
{
    [ConnectModel connctUrl:@"http://api.ycapp.yiche.com/yicheapp/getselectcarpagead" andPost:@"platform=1" block:^(NSData *data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dataDic = [dic objectForKey:@"data"];
        NSMutableArray *masterArray = [dataDic objectForKey:@"hotMaster"];
        for (NSMutableDictionary *dic in masterArray) {
            SecondCellModel *model = [[SecondCellModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.secondCellHotMaster addObject:model];
            [model release];
        }
        NSMutableArray *serialArray = [dataDic objectForKey:@"hotSerial"];
        for (NSMutableDictionary *dic in serialArray) {
            SecondCellModel *model1 = [[SecondCellModel alloc] init];
            [model1 setValuesForKeysWithDictionary:dic];
            [self.secondCellHotSerial addObject:model1];
            [model1 release];
        }
        [self createTableView];
        [self creatHeadView];
    }];
}


#pragma 创建 tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    // 注册Cell
    [self.tableView registerClass:[SecondCell class] forCellReuseIdentifier:@"second"];
    [self.tableView registerClass:[BrandCell class] forCellReuseIdentifier:@"brand"];
    
    [self.tableView release];
    
    self.listView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth * 90 / 375, 0, self.view.frame.size.width - 90, self.view.frame.size.height)];
    
    
    // listTableView(小TableView)的创建
    self.listTableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - kScreenWidth * 90 / 375, self.view.frame.size.height) style:UITableViewStylePlain] autorelease];
    [self.listTableView registerClass:[ListCell class] forCellReuseIdentifier:@"list"];
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    self.listTableView.layer.borderWidth = 0.3;
    self.listTableView.layer.borderColor = [[UIColor grayColor] CGColor];
    
    // 添加listImage图片
    
    self.listTableImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenHeight * 220 / 667, kScreenWidth * 20 / 375, kScreenHeight * 65 / 667)];
    [self.listTableImage setImage:[UIImage imageNamed:@"6.png"]];
    
    [self.listView addSubview:self.listTableView];
    [self.listView addSubview:self.listTableImage];
    
    [self.listTableImage release];
    [self.listView release];
    
}



#pragma tableView两个必走协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        
        if (section == 0) {
            return 1;
        }
        NSString *str = [[self.brandArray[section] allKeys] objectAtIndex:0];
        NSMutableArray *arr = [self.brandArray[section] objectForKey:str];
        return arr.count;
    }
    NSString *str = [[self.listArray[section] allKeys] objectAtIndex:0];
    NSMutableArray *arr = [self.listArray[section] objectForKey:str];
    return arr.count;
}

#pragma 设置cell高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        if (indexPath.row == 0 && indexPath.section == 0) {
            return kScreenHeight * 320 / 667;
        }
        return kScreenHeight * 70 / 667;
    }
    return kScreenHeight * 90 / 667;
}

#pragma 重用池
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SecondCell *second = [tableView dequeueReusableCellWithIdentifier:@"second"];
    BrandCell *brand = [tableView dequeueReusableCellWithIdentifier:@"brand"];
    ListCell *list = [tableView dequeueReusableCellWithIdentifier:@"list"];
    if (tableView == self.tableView) {
        
        if (indexPath.section == 0) {
            
            [second sendMasterArray:self.secondCellHotMaster serialArray:self.secondCellHotSerial];
            second.delegate = self;
            second.serialDelegate = self;
            second.selectionStyle = UITableViewCellSelectionStyleNone;
            return second;
            
        } else {
            
            NSString *str = [[self.brandArray[indexPath.section] allKeys] objectAtIndex:0];
            NSMutableArray *arr = [self.brandArray[indexPath.section] objectForKey:str];
            
            ZBrandModel *model = [arr objectAtIndex:indexPath.row];
            [brand.myImage sd_setImageWithURL:[NSURL URLWithString:model.ZIMAGE] placeholderImage:nil];
            brand.myLabel.text = model.ZNAME;
            return brand;
        }
    }    else   {
        
        NSString *str = [[self.listArray[indexPath.section] allKeys] objectAtIndex:0];
        NSMutableArray *arr = [self.listArray[indexPath.section] objectForKey:str];
        
        ListModel *model = [arr objectAtIndex:indexPath.row];
        [list.listImage sd_setImageWithURL:[NSURL URLWithString:model.ZIMAGEURL] placeholderImage:nil];
        list.nameLabel.text = model.ZNAME;
        list.priceLabel.text = model.ZPRICERANGE;
        return list;
        
    }
    
}

#pragma 返回section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        
        return self.brandArray.count;
    }
    return self.listArray.count;
}

#pragma section的题头
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        
        if (section == 0) {
            return nil;
        }
        return [[self.brandArray[section] allKeys] objectAtIndex:0];
    }
    return [[self.listArray[section] allKeys] objectAtIndex:0];
}

#pragma 添加索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in self.brandArray) {
            [arr addObject:[[dic allKeys] objectAtIndex:0]];
        }
        return  arr;
    }
    return nil;
}

#pragma 索引和section的关联
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

{
    if (tableView == self.tableView) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in self.brandArray) {
            [arr addObject:[[dic allKeys] objectAtIndex:0]];
        }
        
        return [arr indexOfObject:title];
    }
    return 0;
    
}

#pragma TableView点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = self.listView.gestureRecognizers;
    for (UIGestureRecognizer *ges in array) {
        [self.listView removeGestureRecognizer:ges];
    }

    // 添加手势
    UISwipeGestureRecognizer *pan = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    pan.delegate = self;
    [self.listView addGestureRecognizer:pan];
    [pan release];

    __block ChooseCarController *chooseCarController = self;
    if (tableView == self.tableView && indexPath.section != 0) {
        if (self.listView.frame.origin.x == kScreenWidth * 90 / 375) {
            
            [self.listView removeFromSuperview];
            
            [UIView animateWithDuration:0.3 animations:^{
                
                chooseCarController.listView.frame = CGRectMake(chooseCarController.view.frame.size.width, 0, chooseCarController.listView.frame.size.width, chooseCarController.view.frame.size.height);
                
            } completion:^(BOOL finished) {
                
                self.listArray = [NSMutableArray array];
                
                [self editiListTable:indexPath];
                
                [self.view addSubview:self.listView];
                
                [self.listTableView reloadData];
                
                [UIView animateWithDuration:0.5 animations:^{
                    chooseCarController.listView.frame = CGRectMake(kScreenWidth * 90 / 375, 0, chooseCarController.listView.frame.size.width, chooseCarController.view.frame.size.height);
                }];

            }];
            
            } else {
        
        [UIView animateWithDuration:0.5 animations:^{
            chooseCarController.listView.frame = CGRectMake(kScreenWidth * 90 / 375, 0, chooseCarController.listView.frame.size.width, chooseCarController.view.frame.size.height);
        }];
            
            self.listArray = [NSMutableArray array];
            
            [self editiListTable:indexPath];
            
            [self.view addSubview:self.listView];
            
            [self.listTableView reloadData];

    }
        
        
    } else if (tableView == self.listTableView) {
        
        ListModel *model = [self nextControllerModel:indexPath];
        
        DetailCarViewController *detail = [[DetailCarViewController alloc] init];
        
        detail.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:detail animated:YES];
        
        detail.detailModel = model;
        
        [detail release];
        
    }
}


- (void)swipeAction:(UISwipeGestureRecognizer *)pan
{
    //90.0
//    static CGFloat x;
//    CGPoint point = [pan locationInView:pan.view]; // 手势在这个view的位置
//    if (pan.state == UIGestureRecognizerStateBegan) { // 刚点击时手势的坐标
//        x = point.x; // 给静态x赋值
//    }
//    if (pan.state == UIGestureRecognizerStateChanged) { // 判断手势的状态, 如果是改变时, 判断坐标
//        if (self.listView.frame.origin.x >= 90) { // 大于90 视图才会发生变化
//            self.listView.transform = CGAffineTransformTranslate(self.listView.transform, point.x-x, 0);
//            
//        }
//    }
//    
//    if (pan.state == UIGestureRecognizerStateEnded) { // 结束是, 判断此时listView的坐标
//        if (self.listView.frame.origin.x < self.listView.frame.size.width / 2 + 10) {
//            // 这个情况 回来
//            [UIView animateWithDuration:0.2 animations:^{
//                
//                self.listView.frame = CGRectMake(90, 0, self.view.frame.size.width, self.listView.frame.size.height);
//            }];
//        } else {
//            // 这个情况 消失
//            [UIView animateWithDuration:0.2 animations:^{
//                
//                self.listView.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.listView.frame.size.height);
//            }];
//        }
//    }
    __block ChooseCarController *chooseCarController = self;
    [UIView animateWithDuration:0.3 animations:^{
        chooseCarController.listView.frame = CGRectMake(chooseCarController.view.frame.size.width, 0, chooseCarController.view.frame.size.width, chooseCarController.listView.frame.size.height);
    }];
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

#pragma 监听self.tableView是否要开始滑动,如果滑动,把右侧的小view移除
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    __block ChooseCarController *chooseCarController = self;
    if (scrollView == self.tableView) {
        [UIView animateWithDuration:0.5 animations:^{
           chooseCarController.listView.frame =  CGRectMake(chooseCarController.view.frame.size.width, 0, chooseCarController.view.frame.size.width, chooseCarController.listView.frame.size.height);
        }];
    }
    
}

#pragma 编辑小tableView(listTableView), section统一车型
- (void)editiListTable:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dic = [self.brandArray objectAtIndex:indexPath.section];
    NSString *str = [[dic allKeys] objectAtIndex:0];
    ZBrandModel *zModel =[[dic objectForKey:str] objectAtIndex:indexPath.row];
    NSMutableArray *arr = [NSMutableArray array];
    arr = [ListDatabase selectWithBrand:zModel.Z_PK]; // 通过Z_PK来找 对应的model
    
    [self selectArray:arr];
}
- (void)selectArray:(NSMutableArray *)arr
{
    for (int i = 0; i < arr.count; i++) {
        ListModel *model = arr[i];
        if ([model.ZIMAGEURL containsString:@"{0}"]) {
            NSRange range = [model.ZIMAGEURL rangeOfString:@"{0}"];
            NSMutableString *str = [model.ZIMAGEURL mutableCopy];
            [str replaceCharactersInRange:range withString:@"3"];
            model.ZIMAGEURL = [NSMutableString stringWithString:str];
        }
    }
    
    NSMutableArray *arr1 = [NSMutableArray array];
    
    for (ListModel *model in arr) {
        
        for (NSMutableDictionary *dic in self.listArray) {
            [arr1 addObject:[[dic allKeys] objectAtIndex:0]];
        }
        
        if (![arr1 containsObject:model.ZPARENTNAME]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSMutableArray *small = [NSMutableArray array];
            [small addObject:model];
            [dic setObject:small forKey:model.ZPARENTNAME];
            [self.listArray addObject:dic];
        } else {
            int num = 0;
            for (NSMutableDictionary *dic in self.listArray) {
                if ([[[dic allKeys] objectAtIndex:0] isEqualToString:model.ZPARENTNAME]) {
                    [[[self.listArray objectAtIndex:num] objectForKey:model.ZPARENTNAME] addObject:model];
                }
                num++;
            }
        }
    }
    
}


#pragma 编译大数组brandArray, 按字母排序
- (void)editiBrandArray:(NSMutableArray *)bigArray
{
    // 更改model.ZIMAGE的网址,把{0}换成3,否则网址不可用
    for (int i = 0; i < bigArray.count; i++) {
        ZBrandModel *model = bigArray[i];
        if ([model.ZIMAGE containsString:@"{0}"]) {
            NSRange range = [model.ZIMAGE rangeOfString:@"{0}"];
            NSMutableString *str = [model.ZIMAGE mutableCopy];
            [str replaceCharactersInRange:range withString:@"3"];
            model.ZIMAGE = [NSMutableString stringWithString:str];
        }
        
        // 按照首字母排序, 重新排列品牌列表, 数组套字典,字典套model, 重新赋给大数组的属性
        NSMutableArray *arr = [NSMutableArray array];
        for (NSMutableDictionary *dic in self.brandArray) {
            [arr addObject:[[dic allKeys] objectAtIndex:0]];
        }
        // 判断这个大数组中,是否有首字母这个key, 如果没有,新建一个字典,附上首字母的Key,放入数组中
        if (![arr containsObject:model.ZFIRSTLETTER]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSMutableArray *smallArray = [NSMutableArray array];
            
            NSInteger i = arr.count;
            if (i > 0) {
                // 首字母的排序
                if ([model.ZFIRSTLETTER compare:[arr lastObject]] == -1 && [model.ZFIRSTLETTER compare:[arr objectAtIndex:0]] != -1) {
                    while ([model.ZFIRSTLETTER compare:[arr objectAtIndex:i - 1]] == -1) {
                        i--;
                    }
                    [dic setObject:smallArray forKey:model.ZFIRSTLETTER];
                    [smallArray addObject:model];
                    [self.brandArray insertObject:dic atIndex:i];
                } else if ([model.ZFIRSTLETTER compare:[arr objectAtIndex:0]] == -1) {
                    [dic setObject:smallArray forKey:model.ZFIRSTLETTER];
                    [smallArray addObject:model];
                    [self.brandArray insertObject:dic atIndex:0];
                } else {
                    [dic setObject:smallArray forKey:model.ZFIRSTLETTER];
                    [smallArray addObject:model];
                    [self.brandArray addObject:dic];
                }
            } else {
                [dic setObject:smallArray forKey:model.ZFIRSTLETTER];
                [smallArray addObject:model];
                [self.brandArray addObject:dic];
            }
        } else {
            //    根据model.ZFIRSTLETTER  找到数组中对应的首字母, 把这个model加入这个首字母对应的小数组里
            int i = 0;
            for (NSString *str in arr) {
                if ([str isEqualToString:model.ZFIRSTLETTER]) {
                    break;
                }
                i++;
            }
            NSMutableDictionary *dic = [self.brandArray objectAtIndex:i];
            [[dic objectForKey:model.ZFIRSTLETTER] addObject:model];
        }
        
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.secondCellHotMaster forKey:@"#"];
    [self.brandArray insertObject:dic atIndex:0];
    
    
}

#pragma 遍历ListArray数组,点哪传什么值
- (ListModel *)nextControllerModel:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dic = [self.listArray objectAtIndex:indexPath.section];
    NSString *str = [[dic allKeys] objectAtIndex:0];
    NSMutableArray *array = [dic objectForKey:str];
    ListModel *model = [array objectAtIndex:indexPath.row];
    return model;
}

#pragma  hotMaster协议接值, 处理值
- (void)senModel:(SecondCellModel *)model
{
    __block ChooseCarController *chooseCarController = self;
    ZBrandModel *brandModel = [[[ZBrandModel alloc] init] autorelease];
    brandModel = [BrandDatabase selectModel:model.masterId];;
    NSMutableArray *arr = [NSMutableArray array];
    arr = [ListDatabase selectWithBrand:brandModel.Z_PK]; // 通过Z_PK来找 对应的model
    
    [UIView animateWithDuration:0.5 animations:^{
        chooseCarController.listView.frame = CGRectMake(90, 0, chooseCarController.listView.frame.size.width, chooseCarController.view.frame.size.height);
    }];
    
    // 添加手势
    UILongPressGestureRecognizer *pan = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    pan.delegate = self;
    
    //    pan.minimumPressDuration = 0.1;
    [self.listView addGestureRecognizer:pan];
    [pan release];
    
    self.listArray = [NSMutableArray array];
    
    [self selectArray:arr];
    
    [self.view addSubview:self.listView];
    
    [self.listTableView reloadData];
}

#pragma Serial协议接值,处理值
- (void)serialSend:(SecondCellModel *)model
{
    DetailCarViewController *detail = [[DetailCarViewController alloc] init];
    
    detail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detail animated:YES];
    
    detail.cellModel = model;
    
    [detail release];
    
}






















- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
